<template>
  <article
      class="post-card"
      :style="isRemoving ? removingStyles : ''"
  >
    <!-- 作者信息和等级 -->
    <div v-if="post.user?post.user:post.user=userData" class="author-section">
      <div class="author-container">
        <router-link :to="`/user/${post.userId}`" class="author-info">
          <img
              :src="post.user.avatar||'/userTx.svg'"
              class="author-avatar lazy-load"
              @error="handleAvatarError"
          >
          <div>
            <div class="author-meta">
              <p class="author-name">{{ post.user.nickname}}</p>
              <span
                  class="rank-badge"
                  :class="`rank-${post.user.level}`"
              >
                Lv.{{ post.user.level }}
              </span>
              <span class="post-time">{{ formatPostTime(post.publishTime) }}</span>
            </div>
          </div>
        </router-link>

        <!-- 操作控件 -->
        <div class="action-controls">
          <button class="action-button" @click.stop="handleReport">
            <i class="fa fa-flag-o text-red-500">. . .</i>
          </button>
          <button class="action-button" @click.stop="handleNotInterested">
            <i class="fa fa-ban"></i>
          </button>
        </div>
      </div>
    </div>

    <router-link :to="`/post/${post.postId}`" class="content-link">
      <!-- 标题和正文 -->
      <div class="post-content">
        <h2 class="post-title">{{ post.title }}</h2>
        <p class="post-text">
          {{ post.content }}
        </p>
      </div>

      <!-- 图片展示 -->
      <div class="post-images">
        <div
            v-for="(image, index) in post.postImages"
            :key="index"
            :class="`image-container ${imageWidthClass}`"
        >
          <img
              :src="image.imageUrl"
              :alt="`${post.title} ${index + 1}`"
              class="post-image lazy-load"
          >
          <!-- 图片数量徽章 -->
          <span
              class="image-count-badge"
              v-if="index === post.postImages.length - 1&&post.postImages.length>3"
          >
            共{{ post.postImages.length }}张
          </span>
        </div>
      </div>

      <!-- 互动信息和话题标签 -->
      <div class="post-actions">
        <!-- 话题标签 -->
        <div class="tags-container" v-if="post.postTage!=null">
          <span
              class="topic-tag"
              v-for="(tag, index) in post.tags"
              :key="index"
              :class="`tag-${tag.type}`"
          >
            {{ tag.text }}
          </span>
        </div>

        <!-- 互动按钮 -->
        <div class="actions-container">
          <div class="left_actions">
            <button
                class="action-button like-button"
                @click.stop="handleLike"
            >
              <img 
                :src="isLiked ? '/good-job.svg' : '/good-job.svg'" 
                :class="isLiked ? 'icon-svg icon-liked' : 'icon-svg'" 
                alt="点赞" 
              />
              <span>{{ isLiked ? post.likeCount + 1 : post.likeCount }}</span>
            </button>
            <button class="action-button comment-button">
              <img src="/chat-o.svg" alt="评论" class="icon-svg" />
              <span>{{ post.commentCount }}</span>
            </button>
          </div>
          <button
              class="action-button bookmark-button"
              @click.stop="handleBookmark"
          >
            <i :class="isBookmarked ? 'fa fa-bookmark' : 'fa fa-bookmark-o'">收藏</i>
          </button>
        </div>
      </div>
    </router-link>
  </article>
</template>

<script>
export default {
  props: {
    post: {
      type: Object,
      required: true,
      default: () => ({})
    },
    userData:{
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  data() {
    return {
      isLiked: false,
      isBookmarked: false,
      isRemoving: false
    };
  },
  mounted() {
    // 点击外部关闭下拉菜单
    document.addEventListener('click', this.handleClickOutside);

    // 初始化图片懒加载
    this.initLazyLoading();

  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleClickOutside);
  },
  computed: {
    // 根据图片数量计算每张图片的宽度
    imageWidthClass() {
      // const count = this.post.images.length;
      // if (count === 1) return 'image-full';
      // if (count === 2) return 'image-half';
      return 'image-third';
    },
    // 移除动画样式
    removingStyles() {
      return {
        opacity: '0',
        height: '0',
        margin: '0',
        padding: '0',
        overflow: 'hidden'
      };
    }
  },
  methods: {
    handleLike() {
      this.isLiked = !this.isLiked;
    },
    handleBookmark() {
      this.isBookmarked = !this.isBookmarked;
    },
    handleReport() {
      if (confirm('确定要举报并删除此帖子吗?')) {
        this.isRemoving = true;
        // 动画结束后触发移除事件
        setTimeout(() => {
          this.$emit('remove-post', this.post.postId);
        }, 500);
      }
    },
    handleNotInterested() {
      if (confirm('确定对此内容不感兴趣吗？')) {
        this.isRemoving = true;
        // 动画结束后触发移除事件
        setTimeout(() => {
          this.$emit('remove-post', this.post.id);
        }, 500);
      }
    },
    handleClickOutside(event) {
      if (this.$refs.dropdownContainer && !this.$refs.dropdownContainer.contains(event.target)) {
        const dropdown = this.$refs.dropdownContainer.querySelector('.dropdown-menu');
        if (dropdown) {
          dropdown.classList.remove('visible');
        }
      }
    },
    initLazyLoading() {
      if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              const img = entry.target;
              img.classList.add('loaded');
              imageObserver.unobserve(img);
            }
          });
        });

        document.querySelectorAll('.lazy-load').forEach(img => {
          imageObserver.observe(img);
        });
      } else {
        // 降级处理
        document.querySelectorAll('.lazy-load').forEach(img => {
          img.classList.add('loaded');
        });
      }
    },
    // 格式化发布时间
    formatPostTime(publishTime) {
      // 如果publishTime是字符串，转换为Date对象
      const publishDate = typeof publishTime === 'string' ? new Date(publishTime) : publishTime;
      const now = new Date();
      const diffTime = Math.abs(now - publishDate);
      const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
      const diffMonths = Math.floor(diffDays / 30);
      const diffYears = Math.floor(diffDays / 365);

      // 获取星期几
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const weekday = weekdays[publishDate.getDay()];

      // 获取月份和日期
      const month = publishDate.getMonth() + 1;
      const day = publishDate.getDate();
      const year = publishDate.getFullYear();

      if (diffHours < 1) {
        return '刚刚';
      } else if (diffHours < 24) {
        return `${diffHours}小时前`;
      } else if (diffDays < 7) {
        return `${diffDays}天前发布`;
      } else if (diffDays < 30) {
        return `${weekday}`;
      } else if (diffMonths < 12) {
        return `${month}月${day}日发布`;
      } else {
        return `${year}年${month}月${day}日发布`;
      }
    },
    // 处理头像加载错误
    handleAvatarError(e) {
      const target = e.target;
      target.src = '/default-avatar.png';
    }
  }
};

const goDetail=(pid)=>{
  router.push({name:'gDetail',params:{id:pid}})
}
</script>

<style scoped>
/* 基础样式 */
.post-card {
  background-color: white;
  border-radius: 0.25rem;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  margin-bottom: 0.5rem;
}

.post-card:hover {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 作者信息区域 */
.author-section {
  padding: 1.25rem;
  border-bottom: 1px solid #F3F4F6;
}

.author-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.author-avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  object-fit: cover;
  opacity: 0;
  transition: opacity 0.7s ease;
}

.author-meta {
  display: flex;
  align-items: center;
}

.author-name {
  font-size: 0.60rem;
  font-weight: 500;
  color: #111827;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

.post-time {
  margin-left: 0.5rem;
  font-size: 0.75rem;
  color: #6B7280;
}

/* 等级徽章 */
.rank-badge {
  margin-left: 0.5rem;
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.125rem 0.375rem;
  border-radius: 0.25rem;
  color: white;
}

.rank-1 {
  background-color: #9CA3AF;
}

.rank-2 {
  background-color: #10B981;
}

.rank-3 {
  background-color: #3B82F6;
}

.rank-4 {
  background-color: #8B5CF6;
}

.rank-5 {
  background-color: #F59E0B;
}

/* 下拉菜单 */
.action-dropdown {
  position: relative;
  display: inline-block;
}

.action-button {
  color: #6B7280;
  background: none;
  border: none;
  cursor: pointer;
  transition: color 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.action-button:hover {
  color: #1F2937;
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 100%;
  margin-top: 0.5rem;
  width: 10rem;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  padding: 0.25rem 0;
  z-index: 10;
  opacity: 0;
  visibility: hidden;
  transform: translateY(0.5rem);
  transition: all 0.2s ease;
}

.action-dropdown:hover .dropdown-menu {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.dropdown-item {
  width: 100%;
  text-align: left;
  padding: 0.5rem 1rem;
  background: none;
  border: none;
  font-size: 0.875rem;
  color: #4B5563;
  cursor: pointer;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
}

.dropdown-item:hover {
  background-color: #F9FAFB;
}

/* 帖子内容区域 */
.post-content {
  padding: 1.25rem;
  border-bottom: 1px solid #F3F4F6;
}

.post-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: #111827;
  margin: 0 0 0.5rem 0;
}

@media (min-width: 640px) {
  .post-title {
    font-size: 1.5rem;
  }
}

.post-text {
  color: #4B5563;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
}

/* 图片展示区域 */
.post-images {
  display: flex;
  overflow: hidden;
}

.image-container {
  flex-shrink: 0;
  position: relative;
}

.image-full {
  width: 100%;
}

.image-half {
  width: 50%;
}

.image-third {
  width: 33.3333%;
}

.post-image {
  width: 100%;
  height: 7rem;
  object-fit: cover;
  transition: transform 0.5s ease;
  opacity: 0;
  transition: opacity 0.7s ease;
}

.post-image:hover {
  transform: scale(1.05);
}

.image-count-badge {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.25rem 0.5rem;
  border-radius: 9999px;
  backdrop-filter: blur(4px);
}

/* 互动区域 */
.post-actions {
  padding: 1rem;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.topic-tag {
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.125rem 0.625rem;
  border-radius: 9999px;
  transition: opacity 0.2s ease;
}

.topic-tag:hover {
  opacity: 0.9;
}

.tag-blue {
  background-color: #EFF6FF;
  color: #2563EB;
}

.tag-purple {
  background-color: #F9FAFF;
  color: #7C3AED;
}

.tag-green {
  background-color: #ECFDF5;
  color: #059669;
}

.tag-pink {
  background-color: #FDF2F8;
  color: #DB2777;
}

.actions-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #6B7280;
  font-size: 0.875rem;
}

.left_actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.like-button:hover, .comment-button:hover, .bookmark-button:hover {
  color: #2563EB;
}

/* 懒加载样式 */
.lazy-load.loaded {
  opacity: 1;
}

/* SVG图标样式 */
.icon-svg {
  width: 1rem;
  height: 1rem;
  display: inline-block;
  vertical-align: middle;
}

/* 点赞状态下的SVG图标样式 */
.icon-liked {
  filter: invert(16%) sepia(99%) saturate(7459%) hue-rotate(358deg) brightness(96%) contrast(112%);
}

/* 动画过渡 */
.post-card {
  transition: all 0.5s ease;
}
</style>
